from config import GlobalContextData
from pathlib import Path
import configparser

class DbMigrator:
    ConnStr = GlobalContextData.DataBaseConnectionString
    Alembic = Path.cwd() / 'alembic.ini'
    AlembicEnvPy = Path.cwd() / 'alembic' / 'env.py'

    @staticmethod
    def quickly_setting():
        config = configparser.ConfigParser()

        config.read(DbMigrator.Alembic)

        if 'alembic' not in config:
            config.add_section('alembic')

        config['alembic']['sqlalchemy.url'] = DbMigrator.ConnStr

        with open(DbMigrator.Alembic, 'w') as configfile:
            config.write(configfile)

        if DbMigrator.AlembicEnvPy.is_file():
            new_script = DbMigrator.AlembicEnvPy.read_text().replace('target_metadata = None',
                                                        'target_metadata = Database.Base.metadata')
            DbMigrator.AlembicEnvPy.write_text(new_script)


if GlobalContextData.Debug:
    DbMigrator.quickly_setting()
    print(' * Setting database migrate config done')
    print(' * Database migrate: alembic revision --autogenerate -m "Your migration message"')
    print(' * Apply to database: alembic upgrade head')
    print(' * Recovery to database: alembic downgrade <revision_id>')
    print(' * Migration history: alembic history')

